﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ITAP.Core.Modelling.Primitives;
using ITAP.ShprossesBuilder.Calculations;
using ITAP.Core.Modelling;
using ITAP.Core.Calculations;

namespace ITAP.ShprossesBuilder.Modelling.Components.Constraints
{
    [Serializable]
    public class CrossConnectorPositionConstraint : IConstraint
    {
        #region IConstraint Members

        public bool Check(IComponent component)
        {
            return false;
        }

        public void Fix(IComponent component)
        {
            if (!enabled)
                return;

            CrossConnector connector = component as CrossConnector;
            Shpross shpross1 = connector.StartConnectedComponent as Shpross;
            Shpross shpross2 = connector.EndConnectedComponent as Shpross;
            Model model = shpross1.Parent as Model;

            IEndedPrimitive primitive1 = shpross1.Primitives[0] as IEndedPrimitive;
            IEndedPrimitive primitive2 = shpross2.Primitives[0] as IEndedPrimitive;

            ModelPoint[] intersection = primitive1.IntersectMainLines(primitive2, EndType.Start);
            List<ModelPoint> points = new List<ModelPoint>();
            foreach (ModelPoint intersectionPoint in intersection)
                if (primitive1.IsPointInSegment(intersectionPoint, false) && primitive2.IsPointInSegment(intersectionPoint, false))
                    points.Add(intersectionPoint);

            if (points.Count == 0)
            {
                connector.DisconnectFromAll();
                return;
            }

            IEnumerable<ModelPoint> distinct = points.Distinct<ModelPoint>();
            ModelPoint newPosition = ModelCalculations.SortByDistance(connector.Position, distinct)[0];
            connector.MoveTo(newPosition);
             
        }

        private bool enabled = true;
        public bool Enabled
        {
            get
            {
                return enabled;
            }
            set
            {
                enabled = value;
            }
        }

        public ConstraintAction Action
        {
            get { return ConstraintAction.Fix; }
        }
        
        #endregion

        #region ICloneable Members

        public object Clone()
        {
            throw new NotImplementedException();
        }

        #endregion
    }
}
